#include "compiler.h"
#include <regex>

bool compiler::preprocess(int argc,char* argv[]){
    if (argc < 2 || argc > 3){
        printf("错误:参数个数不足--命令格式: panda sourceFile [packagePath]\n");
        return false;
    }
    string packagePath = argc == 3 ? argv[2] : "";
    string packageName = argv[1];
    outputTempFile = ofstream(TEMP_FILE_NAME);
    return import(packagePath,packageName);
}

bool compiler::lexicalAnalysis(){
    ifstream in(TEMP_FILE_NAME,ios::in);
    Scanner scanner(in);
    scanner.lex();

    ofstream out(TOKEN_SEQUENCE,ios::out);
    tokens.show(out);
    return true;
}
bool compiler::grammaticalAnalysis_1(){
    tokens.resetIndex();
    parser.updateNumberOfParsingTimes();
    parser.parse();
    
    if (symbolTable.checkDataMember()){
        ofstream out(DATAMEMBER_INFO);
        symbolTable.showDataMember(out);
        return true;
    }
    return false;
}
bool compiler::grammaticalAnalysis_2(){
    tokens.resetIndex();
    parser.updateNumberOfParsingTimes();
    parser.parse();
    if (symbolTable.checkFunctionMember()){
        ofstream out(FUNCMEMBER_INFO);
        symbolTable.showFunctionMember(out);
        return true;
    }
    return false;
}
bool compiler::grammaticalAnalysis_3(){
    tokens.resetIndex();
    parser.updateNumberOfParsingTimes();
    parser.parse();

    bool flag = true;
    for (auto& node : root){
        if (node->check() == false)
            flag = false;
    }

    if (flag){
        ofstream out(GRAMMAR_TREE);
        for (auto& node : root){
            node->setDeep(0);
            node->show(out);
        }
        return true;
    }
    return false;
}
bool compiler::import(const string& packagePath,string packageName){
    if (importTable.count(packageName) != 0)
        return true;
    else
        importTable.insert(packageName);
    


    for (char& ch : packageName){
        if (ch == '.')
            ch = '/';
    }

    string path = packagePath + packageName + LANGUAGE_EXTENSION;
    ifstream file(path);
    if (file.good() == false){
        printf("错误:导入失败,包%s不存在(定位的路径为%s)\n",packageName.data(),path.data());
        return false;
    }

    string temp;
    bool flag = true;
    char buffer[4096];

    do{
        file.getline(buffer,sizeof(buffer));
        temp = buffer;
        regex e("[ \t]*import[ \t]+([a-zA-Z][a-zA-Z0-9]*(.([a-zA-Z][a-zA-Z0-9]*))*)[ \t]*");
        smatch m;
        bool found = regex_match(temp, m, e);
        if (found == false)
            break;
        if (import(packagePath,m.str(1)) == false)
            flag = false;
        
    }while (true);
    
    outputTempFile << temp;
    while (file.getline(buffer,sizeof(buffer)))
        outputTempFile << buffer << endl;
    
    return flag;
}




bool compiler::compile(){
    root.back()->toAsm();
    return true;
}





